package com.honeybee.cloud.framework.zuul.fallback;

import com.honeybee.cloud.framework.base.exception.ExceptionEnum;
import com.honeybee.cloud.framework.base.exception.business.BaseBizException;
import com.honeybee.cloud.framework.common.response.ResponseEntity;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Description 代理回滚
 * @Author DELL
 * @Create 2018-12-11
 * @Since 1.0.0
 */
public class ZuulFallbackProvider implements FallbackProvider {

    /**
     * 指定为哪一个微服务提供回退
     * *代表所有
     *
     * @return
     */
    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.SERVICE_UNAVAILABLE;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return getErrorText();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(getErrorText().getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                // 设置header
                HttpHeaders headers = new HttpHeaders();
                MediaType mediaType = new MediaType("application",
                        "json", Charset.forName("UTF-8"));
                headers.setContentType(mediaType);
                return headers;
            }

            private String getErrorText(){
                return ResponseEntity.error(BaseBizException.getInstance(ExceptionEnum.SERVICE)).toString();
            }
        };
    }
}
